'use strict';
let mongoose = require('mongoose');
let config = require('../../config')
let InviteGiftCfg = null;

let schema = new mongoose.Schema({
    count : {
        type : Number,
        default : 0
    },
    histroy : {
        type: [require('./gameuser.inviteGift.user')],
        default: []
    }
});

schema.methods = {
    async addInvite(gameUser){
        // if(this.histroy.length < 20){
        //     this.histroy.push({
        //         id : gameUser._id.toString(),
        //         headImgUrl : gameUser.headImgUrl,
        //         nickname : gameUser.nickname,
        //         sex : gameUser.sex,
        //         isGet : false
        //     });
        // }
        // this.count++
    },
    async getInviteCfg(){
        let InviteGiftCfg = mongoose.models['InviteGiftCfg']
        let cfg = null
        if(config.debug){
            cfg = await InviteGiftCfg.find({})
        } else {
            if(!InviteGiftCfg){
                InviteGiftCfg = await InviteGiftCfg.find({})
            }
            cfg = InviteGiftCfg;
        }
        return cfg;
    },
    async getMessage(options){
        let cfg = await this.getInviteCfg()
        return {cfg:cfg,histroy:this.histroy,count:this.count}
    },
    async recevie(options){
        let idx = parseInt(options.idx);
        let user = this.histroy[idx]
        if(!user){
            throw new Error('不存在的位置')
        }
        if(user.isGet){
            throw new Error('已经领取过该奖励')
        }
        let cfg = await this.getInviteCfg();
        let bei = options.bei ? parseInt(options.bei) : 1
        if(idx+1 >= cfg.length){
            throw new Error('当前没有这个奖励')
        }
        let GameUserModel = mongoose.models['GameUser'];
        let gift = cfg[idx]
        let childrens = await GameUserModel.find({parentId:options.self._id.toString()})
        if(childrens.length >= gift.need){
            user.isGet = true;
            options.self.store.goldCoin += gift.props[1]*bei
            options.self.store.diamond += gift.props[0]*bei
            await options.self.save();
            return [gift.props[0]*bei,gift.props[1]*bei];
        } else {
            throw new Error('邀请人数不足')
        }
    }

}

module.exports = schema